﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;


namespace VFramework
{

	/// <summary>
	/// webview，显示外部网页
	/// 由于unity本身显示webview较困难，主要还是桌面端的问题
	/// 故使用electron作为外部程序显示在最顶层，界面上显示为网页嵌套在UI中
	/// </summary>
	public class SinoWebView : MonoBehaviour
	{




		private Canvas rootCanvas = null;

		void Start ()
		{
			injectCanvas ();
		}

		void injectCanvas ()
		{
			rootCanvas = Util.getCanvas (gameObject);
			if (rootCanvas == null) {
				throw new UnityException ("cannot find canvas ????? , webview only attach on Image !!");
			}
		}


		/// <summary>
		/// 显示网页，若没有则更新
		/// </summary>
		/// <returns></returns>
		/// <param name="url">网页地址</param>
		public void showUrl (string url)
		{
			Vector4 b = CalcBounds (rootCanvas, transform);
			url = System.Uri.EscapeDataString (url);        //转码
			open (url, (int)b.z, (int)b.w, (int)b.x, (int)b.y);
		}

		/// <summary>
		/// Open the specified url, pw, ph, px and py.
		/// </summary>
		/// <param name="url">打开的网页地址，已进行了urlencode</param>
		/// <param name="pw">w</param>
		/// <param name="ph">h</param>
		/// <param name="px">x</param>
		/// <param name="py">y</param>
		public void open (string url, int pw, int ph, int px, int py)
		{
			StartCoroutine (sendCMD ("http://127.0.0.1:10088?px="
			+ px + "&py=" + py + "&pw=" + pw + "&ph=" + ph + "&cmd=update&url=" + url));
		}

		/// <summary>
		/// 关闭网页的显示
		/// </summary>
		public void close ()
		{
			StartCoroutine (sendCMD ("http://127.0.0.1:10088?cmd=close"));
		}

		IEnumerator sendCMD (string url)
		{
			WWW w = new WWW (url);
			Debug.Log ("[webview] url=" + url);
			yield return w;
		}


		Vector4 CalcBounds (Canvas canvas, Transform view)
		{
			Vector3 view_screen_pos = Vector3.zero, leftTop = Vector3.zero, size = Vector3.zero;
			CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler> ();
			float offect = (Screen.width / canvasScaler.referenceResolution.x) * (1 - canvasScaler.matchWidthOrHeight)
						   + (Screen.height / canvasScaler.referenceResolution.y) * canvasScaler.matchWidthOrHeight;

			Bounds b = RectTransformUtility.CalculateRelativeRectTransformBounds (transform);
			size = b.size * offect;

			if (canvas.renderMode == RenderMode.ScreenSpaceCamera) {
				Camera cam = canvas.worldCamera;
				view_screen_pos = cam.WorldToScreenPoint (view.position);
				view_screen_pos = new Vector3 (view_screen_pos.x, -view_screen_pos.y + Screen.height);

			} else if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) {
				view_screen_pos = view.position;
				view_screen_pos = new Vector3 (view_screen_pos.x, -view_screen_pos.y + Screen.height, 0);

			} else {
			}
			leftTop = view_screen_pos - size / 2;

			if (Application.productName.StartsWith ("ss_")) {
				leftTop.y += Screen.height;
			}
			Debug.Log ("leftTop=" + leftTop + "   size=" + size);

			return new Vector4 (leftTop.x, leftTop.y, size.x, size.y);
		}


	}
}

/**
//Created by vainner on 16/8/22.
//electron的代码，保存后直接 electron xx.js即可
const e = require ('electron')
var http = require ('http')
var url = require ('url')


var app = e.app;
var window = null;


function makeServer ()
{
	http.createServer (function (request, response) {
		try {
			console.log ('[GET] ' + request.url)
	
	  var arg = require ('querystring').parse (url.parse (request.url).query)
	

	  if (arg ['cmd'] === 'update') {
				if (window === null) {
					makeWindow (arg)
		
		} else {
					updateWindow (arg)

		}
			} else if (arg ['cmd'] === 'close') {
				if (window) {
					window.hide ()
		
		}
			} else {
				throw "no such cmd !"
	  
	  }

			response.writeHead (200, { 'Content-Type': 'text/plain'});
			response.end (JSON.stringify ({ code: 1}));
		} catch (e) {
			response.writeHead (500, { 'Content-Type': 'text/plain'});
			response.end (JSON.stringify ({ code: -1, msg: e}));
		}
	}).listen (10088, '127.0.0.1');

	console.log ("listen 10088~~~~")
  makeWindow ({ pw: 1, ph: 1, px: -10, py: -10, url: 'http://www.baidu.com'})
  window.hide ()
}


function updateWindow (opts)
{

	console.log ('[UPDATE] ' + JSON.stringify (opts))
  window.show ()
  window.setPosition (parseInt (opts ['px']), parseInt (opts ['py']))
  window.setSize (parseInt (opts ['pw']), parseInt (opts ['ph']))
  window.loadURL (opts ['url'])
}


function makeWindow (opts)
{
	window = new e.BrowserWindow ({
	width: parseInt(opts['pw']),
	height: parseInt(opts['ph']),
	'resizable': false,
	'frame': false,
	x: parseInt(opts['px']),
	y: parseInt(opts['py']),
  });

	window.loadURL (opts ['url']);
	if (opts ['debug'] === "1") {
		window.webContents.openDevTools ()
    }

	window.setAlwaysOnTop (true)
  window.on ('close', function () {
		window = null;
	})
}

e.app.on('ready', function ()
{
	makeServer ()
})
**/
